轮询法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class TestRoundRobin {
private static Map<String, Integer> serverWeightMap = new HashMap<>();
static {
serverWeigthMap.put("192.168.1.12", 1);
serverWeigthMap.put("192.168.1.13", 1);
serverWeigthMap.put("192.168.1.14", 2);
serverWeigthMap.put("192.168.1.15", 2);
serverWeigthMap.put("192.168.1.16", 3);
serverWeigthMap.put("192.168.1.17", 3);
serverWeigthMap.put("192.168.1.18", 1);
serverWeigthMap.put("192.168.1.19", 2);
}
Integer pos = 0;
public static String roundRobin() {
Map<String, Integer> serverMap = new HashMap<>();
serverMap.putAll(serverWeightMap);
Set<String> keySet = serverMap.keySet();
ArrayList<String> keyList = new ArrayList<>();
keyList.addAll(keySet);
String server = null;
synchronized(pos) {
if (pos > keySet.size()) {
pos = 0;
}
server = keyList.get(pos);
pos++;
}
return server;
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
String serverIp = roundRobin();
System.out.println(serverIp);
}
}
}

加权轮询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class TestWeightRandom {
private static Map<String, Integer> serverWeightMap = new HashMap<>();
static {
serverWeigthMap.put("192.168.1.12", 1);
serverWeigthMap.put("192.168.1.13", 1);
serverWeigthMap.put("192.168.1.14", 2);
serverWeigthMap.put("192.168.1.15", 2);
serverWeigthMap.put("192.168.1.16", 3);
serverWeigthMap.put("192.168.1.17", 3);
serverWeigthMap.put("192.168.1.18", 1);
serverWeigthMap.put("192.168.1.19", 2);
}
public static String weightRandom() {
Map<String, Integer> serverMap = new HashMap<>();
serverMap.putAll(serverWeightMap);
Set<String> keySet = serverMap.keySet();
Iterator<String> it = keySet,iterator();
List<String> serverList = new ArrayList<>();
while (it.hasNext()) {
String server = it.next();
Integer weight = serverMap.get(server);
for (int i = 0; i < weight; i++) {
serverList.add(server);
}
}
Random random = new Random();
int randomPos = random.nextInt(serverList.size());
String server = serverList.get(randomPos);
return server;
}
public static void main(String[] args) {
String serverIp = weightRandom();
System.out.println(serverIp);
}
}